package com.helpyoutimely.order.service;/**
 * ${PROJET_NAME}
 * Created by lixinkun on 16/4/14 15:12.
 * Email EricLi1235@gmail.com.
 */

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.helpyoutimely.order.OrderActivity;

import java.util.Timer;
import java.util.TimerTask;

/**
 * User: lixinkun
 * Date: 2016-04-14
 * Time: 15:12
 * FIXME
 */
public class CountTimeService extends Service{
    private Timer timer;
    private TimerTask task;
    private Handler handler;
    private long endTime;

    /**
     * 本地广播
     */
    private LocalBroadcastManager mLocalBroadcastManager;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case 1:
                        endTime = System.currentTimeMillis();
                        Log.d("lixnkun","endtime = "+endTime);
                        Intent i = new Intent();
                        i.setAction(OrderActivity.CountTime);
                        i.putExtra(OrderActivity.EndTime,endTime);
                        sendBroadcast(i);
                        break;
                }
                super.handleMessage(msg);

            }
        };
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
        if(intent != null){
            startTimer();
        }
        return START_STICKY;
    }


    private void startTimer(){
        task = new TimerTask() {
            @Override
            public void run() {
                handler.sendEmptyMessage(1);
            }
        };

        timer = new Timer(true);
        timer.schedule(task,1000,1000);
    }

    private void stopTimer(){
        task.cancel();
        task = null;
        timer.cancel();
        timer.purge();
        timer = null;
    }}
